<template>
  <a-modal
    :title="title"
    :width="720"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item label="搜索会员" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select
            show-search
            allowClear
            v-decorator="['user', {rules: [{ required: true, message: '选择会员' }]}]"
            placeholder="输入昵称、手机号、会员ID搜索"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="null"
            @search="handleSearch"
            @change="handleChange"
          >
            <a-select-option v-for="d in userData" :key="d.user_id">
              <template>
                <img style="margin-top: -3px;" width="28" height="28" :src="host + '/uploads/' + d.avatar" alt="用户图片" />
                {{ d.nick_name }}
              </template>
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-if="!isAdd" label="服务分店" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select
            show-search
            allowClear
            v-decorator="['address', {rules: [{ required: true, message: '选择服务分店' }]}]"
            placeholder="选择服务分店"
            option-filter-prop="name"
            :filter-option="filterAddressOption"
            @blur="handleAddressBlur"
            @change="handleAddressChange"
          >
            <a-select-option v-for="(d,index) in addressData" :key="index">
              {{ d.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="服务时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-date-picker
            v-decorator="['service_time', {rules: [{ required: true, message: '选择服务时间' }]}]"
            show-time
            placeholder="选择服务时间"
            @change="onDateChange" />
        </a-form-item>
        <a-form-item label="服务类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-radio-group
            v-decorator="['service_type', {initialValue: 1, rules: [{ required: true, message: '选择服务类型' }]}]"
          >
            <a-radio :value="1">到店</a-radio>
            <a-radio :value="2">上门</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="支付方式" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-radio-group
            v-decorator="['pay_type', {initialValue: 10, rules: [{ required: true, message: '选择服务类型' }]}]"
          >
            <a-radio :value="10">余额支付</a-radio>
            <!--            <a-radio :value='20'>微信支付</a-radio>-->
            <!--            <a-radio :value='30'>线下支付</a-radio>-->
          </a-radio-group>
        </a-form-item>
        <a-form-item label="选择服务" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select
            show-search
            allowClear
            v-decorator="['services', {rules: [{ required: true, message: '选择购买服务' }]}]"
            placeholder="选择购买服务"
            option-filter-prop="goods_name"
            :filter-option="filterServicesOption"
            @blur="handleServicesBlur"
            @change="handleServicesChange"
          >
            <a-select-option v-for="(d,index) in servicesData" :key="index">
              {{ d.goods_name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          v-show="servicesObject && servicesObject.spec_type === 20"
          label="选择规格"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol">
          <a-select
            show-search
            allowClear
            v-decorator="['sku', {rules: [{ type: 'number', message: '选择服务规格' }]}]"
            placeholder="选择服务规格"
            option-filter-prop="sku"
            :filter-option="filterSkuOption"
            @change="handleSkuChange"
          >
            <a-select-option v-for="(d,index) in skuData" :key="index">
              {{ d.sku }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="选择技师" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select
            show-search
            allowClear
            v-decorator="['proficient', {rules: [{ required: true, message: '选择服务技师' }]}]"
            placeholder="选择服务技师"
            option-filter-prop="name"
            :filter-option="filterProficientOption"
            @blur="handleProficientBlur"
            @change="handleProficientChange"
          >
            <a-select-option v-for="(d,index) in proficientData" :key="index">
              {{ d.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import * as Api from '@/api/store/build'
import store from '@/store'
import * as Store from '@/api/store'

export default {
  components: {},
  data () {
    return {
      host: store.getters.publicConfig.HOST,
      user: undefined,
      userObject: null,
      address: undefined,
      addressObject: null,
      service_type: 1,
      services: undefined,
      servicesObject: null,
      sku: undefined,
      skuObject: null,
      proficient: undefined,
      proficientObject: null,

      userData: [],
      addressData: [],
      servicesData: [],
      skuData: [],
      proficientData: [],

      // 对话框标题
      title: '门店下单',
      // 标签布局属性
      labelCol: { span: 7 },
      // 输入框布局属性
      wrapperCol: { span: 13 },
      // modal(对话框)是否可见
      isAdd: false,
      visible: false,
      // modal(对话框)确定按钮 loading
      confirmLoading: false,
      // 当前表单元素
      form: this.$form.createForm(this)
    }
  },
  created () {
    this.storeInfo()
  },
  methods: {
    onDateChange (value, dateString) {
    },
    storeInfo () {
      Store.info().then((result) => {
        const { data: { storeInfo } } = result
        this.isAdd = storeInfo.isAdd
        if (storeInfo.isAdd) {
          this.addressObject = {
            address_id: storeInfo.address_id
          }
          Api.services({ addressId: storeInfo.address_id, serviceType: 1 })
            .then(res => {
              this.servicesData = res.data.goods
            })
        }
      })
    },
    /**
     * 显示对话框
     */
    build () {
      Api.addresses()
        .then(res => {
          this.addressData = res.data.addresses
        })
      // 显示窗口
      this.visible = true
    },

    handleSearch (value) {
      Api.fetchUser({ searchUser: value })
        .then(res => {
          this.userData = res.data.users
        })
    },
    handleChange (value) {
    },
    handleAddressChange (value) {
      this.addressObject = this.addressData[value]

      this.form.setFieldsValue({
        address: this.addressData[value]?.address_id,
        services: undefined,
        sku: undefined,
        proficient: undefined
      })

      this.servicesObject = null
      this.servicesData = []

      this.skuObject = null
      this.skuData = []

      this.proficientObject = null
      this.proficientData = []

      this.form.validateFields((err, values) => {
        Api.services({ addressId: this.addressObject.address_id, serviceType: values.serviceType })
          .then(res => {
            this.servicesData = res.data.goods
          })
      })
    },
    handleAddressBlur () {
    },
    filterAddressOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    handleServicesChange (value) {
      this.servicesObject = this.servicesData[value]
      this.form.setFieldsValue({
        services: this.servicesData[value]?.goods_id,
        sku: undefined,
        proficient: undefined
      })

      this.skuObject = null
      this.skuData = []
      this.proficientObject = null
      this.proficientData = []

      this.form.validateFields((err, values) => {
        Api.skus({ searchGoods: values.services })
          .then(res => {
            this.skuData = res.data.data
          })

        if (this.servicesObject.goods_id && this.addressObject.address_id) {
          Api.proficients({ searchGoods: this.servicesObject.goods_id, addressId: this.addressObject.address_id })
            .then(res => {
              this.proficientData = res.data.proficients
            })
        }
      })
    },
    handleServicesBlur () {
      // if (this.address > 0) {
      //   Api.services({ addressId: this.address, serviceType: this.serviceType })
      //     .then(res => {
      //       this.servicesData = res.data.goods
      //     })
      // }
    },
    filterServicesOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    handleSkuChange (value) {
      console.log(1, value, this.skuData[value]?.id)
      this.form.setFieldsValue({
        sku: parseInt(this.skuData[value]?.id)
      })
      this.skuObject = this.skuData[value]
    },
    handleSkuBlur () {
      // if (this.address > 0) {
      //   Api.services({ addressId: this.address, serviceType: this.serviceType })
      //     .then(res => {
      //       this.servicesData = res.data.goods
      //     })
      // }
    },
    filterSkuOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    handleProficientChange (value) {
      this.form.setFieldsValue({
        proficient: this.proficientData[value]?.id
      })
      this.proficientObject = this.proficientData[value]
    },
    handleProficientBlur () {
      // if (this.address > 0) {
      //   Api.services({ addressId: this.address, serviceType: this.serviceType })
      //     .then(res => {
      //       this.servicesData = res.data.goods
      //     })
      // }
    },
    filterProficientOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },

    /**
     * 确认按钮
     */
    handleSubmit (e) {
      e.preventDefault()
      // 表单验证
      const { form: { validateFields } } = this
      validateFields((errors, values) => {
        console.log(errors, !errors)
        // 提交到后端api
        !errors && this.onFormSubmit(values)
      })
    },

    /**
     * 关闭对话框事件
     */
    handleCancel () {
      this.visible = false

      this.userData = null
      this.userObject = []

      this.addressData = []
      this.addressObject = null

      this.servicesObject = null
      this.servicesData = []

      this.skuObject = null
      this.skuData = []

      this.proficientObject = null
      this.proficientData = []

      this.form.resetFields()
    },

    /**
     * 提交到后端api
     */
    onFormSubmit (values) {
      this.confirmLoading = true
      Api.add({
        form: {
          user_id: values.user, // 用户ID
          pay_type: values.pay_type, // 支付方式
          service_type: values.service_type, // 服务类型
          address_id: this.addressObject.address_id, // 地址ID
          sku_id: this.skuObject?.id, // 规格
          goods_id: this.servicesObject.goods_id, // 商品ID
          proficient_id: this.proficientObject.id, // 技师ID
          service_time: values.service_time // 服务时间
        }
      })
        .then((result) => {
          // 显示成功
          this.$message.success(result.message, 1.5)
          // 关闭对话框事件
          this.handleCancel()
          // 通知父端组件提交完成了
          this.$emit('handleSubmit', values)
        })
        .finally(() => {
          this.confirmLoading = false
        })
    }
  }
}
</script>
